package com.ruoyi.busi.guide.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.web.core.BaseController;
import com.ruoyi.common.core.core.domain.R;
import com.ruoyi.common.orm.core.page.TableDataInfo;
import com.ruoyi.busi.guide.domain.*;
import com.ruoyi.busi.guide.domain.dto.MentorDetailDTO;
import com.ruoyi.busi.guide.domain.dto.MentorRequestDTO;
import com.ruoyi.busi.guide.service.IMentorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 导师信息Controller
 */
@RestController
@RequestMapping("/busi/guide/mentor")
public class MentorController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(MentorController.class);
    
    @Autowired
    private IMentorService mentorService;

    /**
     * 查询导师列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Mentor mentor) {
        startPage();
        List<Mentor> list = mentorService.selectMentorList(mentor);
        return getDataTable(list);
    }

    /**
     * 获取导师详细信息(包含教育经历和工作经历)
     */
    @GetMapping(value = "/{mentorId}")
    public R getInfo(@PathVariable("mentorId") Long mentorId) {
        MentorDetailDTO detail = mentorService.getMentorDetail(mentorId);
        return R.ok(detail);
    }

    /**
     * 新增导师
     */
    @PostMapping
    public R add(@RequestBody Map<String, Object> requestData) {
        log.info("接收到新增导师请求，原始数据: {}", requestData);
        
        // 转换字段名
        MentorRequestDTO mentorDTO = new MentorRequestDTO();
        log.debug("开始转换基础信息字段");
        mentorDTO.setName((String) requestData.get("name"));
        mentorDTO.setGender((String) requestData.get("gender"));
        mentorDTO.setPhone((String) requestData.get("phone"));
        mentorDTO.setEmail((String) requestData.get("email"));
        mentorDTO.setOrganization((String) requestData.get("organization"));
        mentorDTO.setProfessionalField((String) requestData.get("professionalField"));
        mentorDTO.setHighestEducation((String) requestData.get("highestEducation"));
        mentorDTO.setGoodAtStage((String) requestData.get("goodAtStage"));
        mentorDTO.setPhotoUrl((String) requestData.get("photoUrl"));
        mentorDTO.setIntroduction((String) requestData.get("introduction"));
        
        // 日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        
        // 转换教育经历
        log.debug("开始转换教育经历");
        List<Map<String, String>> educationBackground = (List<Map<String, String>>) requestData.get("educationBackground");
        if (educationBackground != null) {
            List<Education> educations = educationBackground.stream()
                .map(item -> {
                    Education education = new Education();
                    education.setSchool(item.get("school"));
                    education.setDegree(item.get("degree"));
                    education.setMajor(item.get("major"));
                    try {
                        String startDate = item.get("startDate");
                        String endDate = item.get("endDate");
                        if (startDate != null && !startDate.isEmpty()) {
                            education.setStartDate(dateFormat.parse(startDate));
                        }
                        if (endDate != null && !endDate.isEmpty()) {
                            education.setEndDate(dateFormat.parse(endDate));
                        }
                    } catch (ParseException e) {
                        log.error("日期格式转换错误", e);
                        throw new RuntimeException("日期格式应为yyyy-MM", e);
                    }
                    education.setDescription(item.get("description"));
                    return education;
                })
                .collect(Collectors.toList());
            mentorDTO.setEducations(educations);
        }
        
        // 转换工作经历
        log.debug("开始转换工作经历");
        List<Map<String, String>> workExperience = (List<Map<String, String>>) requestData.get("workExperience");
        if (workExperience != null) {
            List<Experience> experiences = workExperience.stream()
                .map(item -> {
                    Experience experience = new Experience();
                    experience.setCompany(item.get("company"));
                    experience.setPosition(item.get("position"));
                    experience.setDepartment(item.get("department"));
                    try {
                        String startDate = item.get("startDate");
                        String endDate = item.get("endDate");
                        if (startDate != null && !startDate.isEmpty()) {
                            experience.setStartDate(dateFormat.parse(startDate));
                        }
                        if (endDate != null && !endDate.isEmpty()) {
                            experience.setEndDate(dateFormat.parse(endDate));
                        }
                    } catch (ParseException e) {
                        log.error("日期格式转换错误", e);
                        throw new RuntimeException("日期格式应为yyyy-MM", e);
                    }
                    experience.setDescription(item.get("description"));
                    return experience;
                })
                .collect(Collectors.toList());
            mentorDTO.setExperiences(experiences);
        }
        
        // 转换能力评估
        log.debug("开始转换能力评估");
        Map<String, Object> abilities = (Map<String, Object>) requestData.get("ability");
        if (abilities != null) {
            Ability ability = new Ability();
            ability.setTechnicalAbility(((Number) abilities.get("technicalAbility")).doubleValue());
            ability.setManagementAbility(((Number) abilities.get("managementAbility")).doubleValue());
            ability.setCommunicationAbility(((Number) abilities.get("communicationAbility")).doubleValue());
            ability.setInnovationAbility(((Number) abilities.get("innovationAbility")).doubleValue());
            ability.setTeachingAbility(((Number) abilities.get("teachingAbility")).doubleValue());
            ability.setResearchAbility(((Number) abilities.get("researchAbility")).doubleValue());
            ability.setMentoringAbility(((Number) abilities.get("mentoringAbility")).doubleValue());
            mentorDTO.setAbilities(ability);
        }
        
        // 转换DTO到实体
        log.debug("开始构建导师实体");
        Mentor mentor = new Mentor();
        mentor.setName(mentorDTO.getName());
        mentor.setGender(mentorDTO.getGender());
        mentor.setPhone(mentorDTO.getPhone());
        mentor.setEmail(mentorDTO.getEmail());
        mentor.setOrganization(mentorDTO.getOrganization());
        mentor.setProfessionalField(mentorDTO.getProfessionalField());
        mentor.setHighestEducation(mentorDTO.getHighestEducation());
        mentor.setTeamCount(mentorDTO.getTeamCount());
        mentor.setGoodAtStage(mentorDTO.getGoodAtStage());
        mentor.setStatus(mentorDTO.getStatus());
        mentor.setTaskProgress(mentorDTO.getTaskProgress());
        mentor.setPhotoUrl(mentorDTO.getPhotoUrl());
        mentor.setIntroduction(mentorDTO.getIntroduction());
        
        // 保存导师信息及关联数据
        log.info("准备保存导师信息，转换后的DTO: {}", mentorDTO);
        boolean result = mentorService.saveWithExperiences(mentor, mentorDTO.getEducations(), mentorDTO.getExperiences(), mentorDTO);
        log.info("保存导师信息结果: {}", result);
        return R.ok(result);
    }

    /**
     * 修改导师及其关联的教育经历、工作经历和能力评估
     */
    @PutMapping
    public R edit(@RequestBody Map<String, Object> requestData) {
        log.info("接收到更新导师请求，原始数据: {}", requestData);
        
        // 转换字段名
        MentorRequestDTO mentorDTO = new MentorRequestDTO();
        log.debug("开始转换基础信息字段");
        mentorDTO.setName((String) requestData.get("name"));
        mentorDTO.setGender((String) requestData.get("gender"));
        mentorDTO.setPhone((String) requestData.get("phone"));
        mentorDTO.setEmail((String) requestData.get("email"));
        mentorDTO.setOrganization((String) requestData.get("organization"));
        mentorDTO.setProfessionalField((String) requestData.get("professionalField"));
        mentorDTO.setHighestEducation((String) requestData.get("highestEducation"));
        mentorDTO.setGoodAtStage((String) requestData.get("goodAtStage"));
        mentorDTO.setPhotoUrl((String) requestData.get("photoUrl"));
        mentorDTO.setIntroduction((String) requestData.get("introduction"));
        
        // 日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        
        // 转换教育经历
        log.debug("开始转换教育经历");
        List<Map<String, String>> educationBackground = (List<Map<String, String>>) requestData.get("educationBackground");
        List<Education> educations = null;
        if (educationBackground != null) {
            educations = educationBackground.stream()
                .map(item -> {
                    Education education = new Education();
                    education.setSchool(item.get("school"));
                    education.setDegree(item.get("degree"));
                    education.setMajor(item.get("major"));
                    try {
                        String startDate = item.get("startDate");
                        String endDate = item.get("endDate");
                        if (startDate != null && !startDate.isEmpty()) {
                            education.setStartDate(dateFormat.parse(startDate));
                        }
                        if (endDate != null && !endDate.isEmpty()) {
                            education.setEndDate(dateFormat.parse(endDate));
                        }
                    } catch (ParseException e) {
                        log.error("日期格式转换错误", e);
                        throw new RuntimeException("日期格式应为yyyy-MM", e);
                    }
                    education.setDescription(item.get("description"));
                    return education;
                })
                .collect(Collectors.toList());
            mentorDTO.setEducations(educations);
        }
        
        // 转换工作经历
        log.debug("开始转换工作经历");
        List<Map<String, String>> workExperience = (List<Map<String, String>>) requestData.get("workExperience");
        List<Experience> experiences = null;
        if (workExperience != null) {
            experiences = workExperience.stream()
                .map(item -> {
                    Experience experience = new Experience();
                    experience.setCompany(item.get("company"));
                    experience.setPosition(item.get("position"));
                    experience.setDepartment(item.get("department"));
                    try {
                        String startDate = item.get("startDate");
                        String endDate = item.get("endDate");
                        if (startDate != null && !startDate.isEmpty()) {
                            experience.setStartDate(dateFormat.parse(startDate));
                        }
                        if (endDate != null && !endDate.isEmpty()) {
                            experience.setEndDate(dateFormat.parse(endDate));
                        }
                    } catch (ParseException e) {
                        log.error("日期格式转换错误", e);
                        throw new RuntimeException("日期格式应为yyyy-MM", e);
                    }
                    experience.setDescription(item.get("description"));
                    return experience;
                })
                .collect(Collectors.toList());
            mentorDTO.setExperiences(experiences);
        }
        
        // 转换能力评估
        log.debug("开始转换能力评估");
        Map<String, Object> abilities = (Map<String, Object>) requestData.get("ability");
        if (abilities != null) {
            Ability ability = new Ability();
            ability.setTechnicalAbility(((Number) abilities.get("technicalAbility")).doubleValue());
            ability.setManagementAbility(((Number) abilities.get("managementAbility")).doubleValue());
            ability.setCommunicationAbility(((Number) abilities.get("communicationAbility")).doubleValue());
            ability.setInnovationAbility(((Number) abilities.get("innovationAbility")).doubleValue());
            ability.setTeachingAbility(((Number) abilities.get("teachingAbility")).doubleValue());
            ability.setResearchAbility(((Number) abilities.get("researchAbility")).doubleValue());
            ability.setMentoringAbility(((Number) abilities.get("mentoringAbility")).doubleValue());
            mentorDTO.setAbilities(ability);
        }
        
        // 转换DTO到实体
        log.debug("开始构建导师实体");
        Mentor mentor = new Mentor();
        mentor.setMentorId(Long.parseLong(requestData.get("mentorId").toString()));
        mentor.setName(mentorDTO.getName());
        mentor.setGender(mentorDTO.getGender());
        mentor.setPhone(mentorDTO.getPhone());
        mentor.setEmail(mentorDTO.getEmail());
        mentor.setOrganization(mentorDTO.getOrganization());
        mentor.setProfessionalField(mentorDTO.getProfessionalField());
        mentor.setHighestEducation(mentorDTO.getHighestEducation());
        mentor.setTeamCount(mentorDTO.getTeamCount());
        mentor.setGoodAtStage(mentorDTO.getGoodAtStage());
        mentor.setStatus(mentorDTO.getStatus());
        mentor.setTaskProgress(mentorDTO.getTaskProgress());
        mentor.setPhotoUrl(mentorDTO.getPhotoUrl());
        mentor.setIntroduction(mentorDTO.getIntroduction());
        
        // 更新导师信息及关联数据
        log.info("准备更新导师信息，转换后的DTO: {}", mentorDTO);
        boolean result = mentorService.updateWithExperiences(mentor, educations, experiences, mentorDTO);
        log.info("更新导师信息结果: {}", result);
        return R.ok(result);
    }

    /**
     * 删除导师
     */
    @DeleteMapping("/{mentorIds}")
    public R remove(@PathVariable List<Long> mentorIds) {
        return R.ok(mentorService.deleteMentorByIds(mentorIds));
    }
}
